

import { useState, useEffect } from 'react';
import _ from 'lodash';

function useColumnSet({originColumns, addedColumns, removedColumns, columnSet}) {
    const [columnsInPanel, setColumnsInPanel] = useState([]);
    const {getCachedByKey, setCachedByKey, cacheKey} = columnSet || {};
    let cachedColumns = getCachedByKey && getCachedByKey(cacheKey);

    useEffect(() => {
        initColumnsInPanel();
    }, [originColumns, addedColumns.current, removedColumns.current])

    const initColumnsInPanel = () => {
        let _columnsInPanel = [];
        let shouldUpdateCache = false;
        if(cachedColumns) {
			// 完善cachedColumns 按道理来说,cached中只需要存一个key，其他的参数引用最新传入的Columns
			cachedColumns = _.map(cachedColumns, (col) => {
				const targetCol = _.find(originColumns, {key: col.key});
				if(targetCol) {
					return { ...targetCol, checked: col.checked } //按道理是可以遍历targetCol所有属性，但防止有导致老逻辑bug就先替换titile属性
				} else {
					return col;
				}
			})
            _columnsInPanel = cachedColumns;
            if(!_.isEmpty(addedColumns.current)) {
                _columnsInPanel = [...cachedColumns, ...addedColumns.current];
                shouldUpdateCache = true;
            }
            if(!_.isEmpty(removedColumns.current)) {
                _columnsInPanel = _.filter(cachedColumns, (t) => {
                    return _.findIndex(removedColumns.current, { key: t.key }) == -1; 
                })
                shouldUpdateCache = true;
            }
			_columnsInPanel = convertFormColumn(_columnsInPanel);
        } else {
            _columnsInPanel = convertFormColumn(originColumns);
        }

        if(shouldUpdateCache) {
            setCachedByKey && setCachedByKey(cacheKey, _.uniqBy(_columnsInPanel, 'key'));
        }
    
        setColumnsInPanel(_columnsInPanel);
    }

    const convertFormColumn = (columns) => {
        //先过滤掉ignored和cache里面已经有的column
        const _columns = _.filter(columns, (col) => {
            return !col.ignored //&& !_.find(cachedColumns, {key: col.key})
        })
        return _.map(_columns, (col) => {
            return {
                checked: col.checked === false ? false : true,
                key: col.key,
                label: typeof col.title === 'string' ? col.title : col.customTitle
            }
        })
    }

    const updateColumnsInPanel = (cachedColumns) => {
        setColumnsInPanel(cachedColumns);
        setCachedByKey && setCachedByKey(cacheKey, _.uniqBy(cachedColumns, 'key'));
    }

    return {
        columnsInPanel,
        updateColumnsInPanel
    }
}

export default useColumnSet;